<script setup>
import {
  reactive,
  ref,
  onMounted,
  defineProps,
  defineExpose,
  computed
} from "vue";
import {
  getSenceImageByUserId,
  getSenceImageBySenceId,
  updateSenceImage,
  deleteSenceImage,
  bindImageSence,
  bindSenceImage,
  getBindSenceIds,
  bindOneImageSence
} from "../../../api/collect";
import { imageFileUpload } from "../../../api/file.js";
import SvgIcon from "../../../components/SvgIcon.vue";
import { ElMessage } from "element-plus";
import {
  downLoadByUrl,
  base64toFile
} from "../../../../static/CIM/BQGIS-downBase64";
import { getSceneList } from "../../../api/system";

const userLoading = ref(true);
const sceneLoading = ref(true);
const userId = window.sessionStorage.getItem("userId");
const sceneCollection = ref([]);
const userCollection = ref([]);
const dialogVisible = ref(false);
const checkList = ref([]);
let currentImageId = "";
const sceneList = ref([]);
const menu = ref(userId);

getUserCollection();
getSceneCollection();

getSceneList().then(res => {
  sceneList.value = res;
});

function onChangeMenu(menuData) {
  menu.value = menuData;
  if (menuData !== "user") {
    getSceneCollection(menuData);
  }
}

function getUserCollection() {
  userLoading.value = true;
  userCollection.value = [];
  getSenceImageByUserId({ userId: userId })
    .then(res => {
      userLoading.value = false;
      userCollection.value = res.map(item => {
        return {
          ...item,
          baseName: item.name, // 修改名称失败后，复原修改
          nameState: 0, // 修改名称的状态 0: 没有修改/完成修改， 1: 正在修改，  2: 正在保存
          imgState: false // 修改图片的状态  true: 正在修改， false: 没有修改/完成修改
        };
      });
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "获取收藏列表失败"
      });
    })
    .finally(() => {
      userLoading.value = false;
    });
}

function getSceneCollection(senceId) {
  sceneLoading.value = true;
  sceneCollection.value = [];
  getSenceImageBySenceId({ senceId })
    .then(res => {
      sceneLoading.value = false;
      sceneCollection.value = res;
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "获取收藏列表失败"
      });
    })
    .finally(() => {
      sceneLoading.value = false;
    });
}

function onBindScene(data) {
  getBindSenceIds({ id: data.id })
    .then(res => {
      checkList.value = res;
      dialogVisible.value = true;
      currentImageId = data.id;
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "获取绑定场景列表失败"
      });
    });
}

function c_collection(id) {
  userLoading.value = true;
  deleteSenceImage({ id }).then(res => {
    getUserCollection();
  });
}

function unbindScene(id) {
  bindOneImageSence({
    senceId: menu.value,
    imageId: id,
    flag: false
  })
    .then(res => {
      ElMessage({
        message: res.msg
      });
      getSceneCollection(menu.value);
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "解除绑定失败"
      });
    });
}

function saveName(item) {
  item.nameState = 2;
  updateSenceImage({
    id: item.id,
    name: item.name,
    userId: item.userid,
    url: item.url,
    camerapose: item.camerapose
  })
    .then(res => {
      item.baseName = item.name;
      ElMessage({
        message: "修改完成"
      });
      item.nameState = 0;
    })
    .catch(res => {
      ElMessage({
        message: "修改失败"
      });
      item.nameState = 1;
    });
}

function cancelName(item) {
  item.name = item.baseName;
  item.nameState = 0;
}

function onEdit(currentData) {
  if (currentData.imgState) return; // 正在修改中
  currentData.imgState = true;
  viewer
    .expImage({ download: false, type: "image/png" })
    .then(e => {
      const f = new FormData();
      const file = base64toFile(e.image, currentData.name);
      f.append("file", file);
      f.append("module", "collect");
      return imageFileUpload(f);
    })
    .then(res => {
      const cartographic = viewer.camera.positionCartographic;
      return updateSenceImage({
        id: currentData.id,
        name: currentData.name,
        userId: currentData.userid,
        url: res.path,
        camerapose: JSON.stringify({
          position: viewer.camera.position,
          lngLatPoint: {
            lng: Cesium.Math.toDegrees(cartographic.longitude),
            lat: Cesium.Math.toDegrees(cartographic.latitude),
            alt: cartographic.height
          },
          heading: Cesium.Math.toDegrees(viewer.camera.heading),
          pitch: Cesium.Math.toDegrees(viewer.camera.pitch),
          roll: Cesium.Math.toDegrees(viewer.camera.roll)
        })
      });
    })
    .then(() => {
      getUserCollection();
      ElMessage({
        message: "修改完成"
      });
    })
    .catch(err => {
      console.error(err);
      ElMessage({
        message: "修改失败"
      });
    })
    .finally(() => {
      currentData.imgState = false;
    });
}

function onDown(item) {
  downLoadByUrl(item.url, item.name);
}

function flyTo(data) {
  const camerapose = JSON.parse(data.camerapose);
  viewer.camera.flyTo({
    destination: camerapose.position, // 设置位置
    orientation: {
      heading: Cesium.Math.toRadians(camerapose.heading), // 方向
      pitch: Cesium.Math.toRadians(camerapose.pitch), // 倾斜角度
      roll: Cesium.Math.toRadians(camerapose.roll)
    }
  });
}

function setScene() {
  bindImageSence({
    senceIds: checkList.value,
    imageId: currentImageId
  })
    .then(res => {
      dialogVisible.value = false;
      ElMessage({
        message: res.msg
      });
    })
    .catch(err => {
      ElMessage({
        message: "绑定场景失败"
      });
    });
}

function cancel() {
  dialogVisible.value = false;
  checkList.value = [];
}

defineExpose({ getUserCollection });
</script>
<template>
  <div class="collection-container">
    <el-menu
      :default-active="menu"
      mode="horizontal"
      background-color="rgba(0,0,0,0.6)"
      text-color="#fff"
      active-text-color="#ffd04b"
      style="height: 10%"
      @select="onChangeMenu"
    >
      <el-menu-item :index="userId">用户收藏夹</el-menu-item>
      <el-sub-menu index="scene">
        <template #title>场景收藏夹</template>
        <el-menu-item :index="scene.id" v-for="scene in sceneList" :key="scene.id">{{scene.name}}</el-menu-item>
      </el-sub-menu>
    </el-menu>
    <div
      class="collection-box"
      id="frame-list"
      v-loading="userLoading"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      v-show="menu === userId"
    >
      <div class="collection-item" :key="item.id" v-for="item in userCollection">
        <div class="item-title">
          <div class="edit-name" v-if="item.nameState === 1 || item.nameState === 2">
            <el-input
              class="edit-input"
              v-if="item.nameState === 1 || item.nameState === 2"
              :disabled="item.nameState === 2"
              v-model="item.name"
              size="small"
            />
            <SvgIcon class="edit-icon" icon="save" @click="saveName(item)" />
            <SvgIcon class="edit-icon" icon="cancel" @click="cancelName(item)" />
          </div>
          <el-tooltip content="双击修改名称" placement="top" v-if="item.nameState === 0">
            <div
              @dblclick="item.nameState = 1"
              style="cursor: pointer"
            >{{item.name}}</div>
          </el-tooltip>
        </div>
        <div class="item-content">
          <img v-loading="item.imgState" class="picture" :src="item.url" />
          <div class="menu">
            <el-tooltip content="定位" placement="right">
              <SvgIcon class="icon" icon="flyTo" @click="flyTo(item)"></SvgIcon>
            </el-tooltip>
            <el-tooltip content="取消收藏" placement="right">
              <SvgIcon class="icon" icon="close" @click="c_collection(item.id)" />
            </el-tooltip>
            <el-tooltip content="修改为当前位置" placement="right">
              <SvgIcon
                class="icon"
                :style="{cursor: item.imgState ? 'no-drop' : 'pointer'}"
                icon="edit"
                @click="onEdit(item)"
              />
            </el-tooltip>
            <el-tooltip content="下载图片" placement="right">
              <SvgIcon class="icon" icon="down" @click="onDown(item)" />
            </el-tooltip>
            <el-tooltip content="绑定场景" placement="right">
              <SvgIcon class="icon" icon="bind" @click="onBindScene(item)" />
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>

    <div
      class="collection-box"
      id="frame-list"
      v-loading="sceneLoading"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      v-show="menu != 'user'"
    >
      <div class="collection-item" :key="item.id" v-for="item in sceneCollection">
        <div class="item-title">{{item.name}}</div>

        <div class="scene-content">
          <img class="picture" :src="item.url" />
          <div class="menu">
            <div class="menu-name">创建人: {{item.username}}</div>
            <div>
              <el-tooltip content="定位" placement="right">
                <SvgIcon class="icon" icon="flyTo" @click="flyTo(item)"></SvgIcon>
              </el-tooltip>
              <el-tooltip content="取消绑定" placement="right">
                <SvgIcon class="icon" icon="close" @click="unbindScene(item.id)" />
              </el-tooltip>
              <el-tooltip content="下载图片" placement="right">
                <SvgIcon class="icon" icon="down" @click="onDown(item)" />
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div>
      <div class="popup_wrapper" v-if="dialogVisible">
        <div class="popup">
          <div class="popup_header">
            <span>绑定场景</span>
            <i class="el-icon-close" @click="dialogVisible = false"></i>
          </div>
          <div class="popup_body">
            <div class="popup-item">
              <el-checkbox-group v-model="checkList">
                <el-checkbox v-for="item in sceneList" :label="item.id" :key="item.id">
                  <div style="display: flex; align-items: center">
                    <span style="color: #fff; margin-right: 3px">{{item.name }}</span>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <div class="popup_footer">
            <el-button type="primary" @click="setScene">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.collection-container {
  height: 430px;
  width: 350px;
  .collection-box {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    height: 85%;
    padding: 10px;
    margin-top: 10px;
    overflow-y: auto;
    box-sizing: border-box;
    .collection-item {
      width: 100%;
      height: 195px;
      margin: 10px;
      border-radius: 10px;
      background: linear-gradient(
        180deg,
        rgba(12, 49, 75, 0.6) 0%,
        rgba(0, 0, 0, 0.6) 100%
      );
      .item-title {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 15%;
        font-size: 14px;
        color: #fff;
        .edit-name {
          display: flex;
          align-items: center;
          .edit-icon {
            color: #fff;
            font-size: 24px;
            cursor: pointer;
            margin-left: 10px;
          }
        }
      }
      .item-content {
        display: flex;
        justify-content: space-between;
        height: 80%;
        padding: 0 10px;
        .picture {
          width: 92%;
          height: 100%;
        }
        .menu {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          width: 5%;
          .icon {
            color: #fff;
            font-size: 15px;
            cursor: pointer;
          }
        }
      }
      .scene-content {
        height: 80%;
        padding: 0 20px;
        .picture {
          width: 100%;
          height: 90%;
        }
        .menu {
          display: flex;
          justify-content: space-between;
          height: 10%;
          color: #fff;
          .menu-name {
            font-size: 12px;
          }
          .icon {
            font-size: 15px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }
  .img {
    width: 32px;
    height: 32px;
  }
}

.popup_wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: 0;
  z-index: 1002;
  background-color: rgba(0, 0, 0, 0.4);

  .popup {
    margin: 100px auto;
    width: 530px;
    background: linear-gradient(
      180deg,
      rgba(30, 144, 255, 0.3) 0%,
      rgba(0, 0, 0, 0.3) 100%
    );
    border: 1px solid #acd38f;
    border-radius: 6px;
    color: white;

    .popup_header {
      width: 100%;
      height: 35px;
      line-height: 35px;
      font-size: 16px;
      display: flex;
      justify-content: space-between;
      color: #fff;
      border-bottom: 2px solid #3c4e60;
      span {
        padding: 0px 10px;
      }

      i {
        width: 12px;
        height: 12px;
        margin: 10px;
        cursor: pointer;
      }
    }

    .popup_body {
      margin: 0 10px;
    }

    .popup_footer {
      width: calc(100% - 30px);
      height: 50px;
      text-align: right;
      padding-right: 30px;
      line-height: 50px;
      border-top: 1px solid #3c4e60;

      .el-button {
        margin-left: 10px;
        height: 30px;
        background: transparent;
        border: 1px solid #acd38f;
        color: #acd38f;
        border-radius: 4px;
        padding: 8px 20px;
      }
    }
  }

  .wide {
    width: 505px;
  }
}
</style>
